package com.budwk.app.sqfwV2.service.povertyMonitoring.impl;

import cn.hutool.json.JSONUtil;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.PersonInfo;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.PersonInfoService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwV2.dto.entity.SqfwHouseholdRegistrationInfo;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.QueryTimeBuildDTO;
import com.budwk.app.sqfwV2.dto.vo.HouseholdRegistrationInfoVO;
import com.budwk.app.sqfwV2.dto.vo.PersonInfoVO;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.QuarterEnum;
import com.budwk.app.sqfwV2.service.povertyMonitoring.HouseholdRegistrationInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.upload.TempFile;
import org.springframework.util.ObjectUtils;

import java.util.Calendar;
import java.util.List;

@Slf4j
@IocBean(args = {"refer:dao"})
public class HouseholdRegistrationInfoServiceImpl extends BaseServiceImpl<SqfwHouseholdRegistrationInfo> implements HouseholdRegistrationInfoService {
    public HouseholdRegistrationInfoServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SysUserService userService;

    @Inject
    private PersonInfoService personInfoService;

    @Inject
    private SqfwFormsummaryNewService formsummaryNewService;

    @Override
    public Result<?> getHouseholdRegistrationInfoPage(HouseholdRegistrationInfoVO householdRegistrationInfoVO) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String content = householdRegistrationInfoVO.getContent();
        String houseType = householdRegistrationInfoVO.getHouseType();
        String checkStatus = householdRegistrationInfoVO.getCheckStatus();
        QuarterEnum quarterEnum = QuarterEnum.getQuarterEnumByMonth(month);

        if (ObjectUtils.isEmpty(quarterEnum)) {
            throw new ServiceException("管理人员未配置月份季度，请先配置！");
        }
        String startTime = null;
        String endTime = null;
        int startTimeQ = Integer.parseInt(quarterEnum.getStartTime());
        int endTimeQ = Integer.parseInt(quarterEnum.getEndTime());
        if (startTimeQ > endTimeQ) {
            //跨年
            if (startTimeQ <= month) {
                startTime = String.format("%s-%s", year, quarterEnum.getStartTime());
                endTime = String.format("%s-%s", year + 1, quarterEnum.getEndTime());
            } else {
                startTime = String.format("%s-%s", year - 1, quarterEnum.getStartTime());
                endTime = String.format("%s-%s", year, quarterEnum.getEndTime());
            }
        } else {
            startTime = String.format("%s-%s", year, quarterEnum.getStartTime());
            endTime = String.format("%s-%s", year, quarterEnum.getEndTime());
        }

        Sys_user user = userService.getUserById(SecurityUtil.getUserId());

        StringBuilder sqlStr = new StringBuilder();
        //StringBuilder sqlStrCount = new StringBuilder();
        sqlStr.append(" select * from (");
        sqlStr.append(" select *, ");
        sqlStr.append(" (select count(*)  from shequ.sqfw_person_info spi ");
        sqlStr.append(" where spi.household_id=shri.id ");
        sqlStr.append(" and deleted !=true ");
        sqlStr.append(" and (( spi.check_update is not null and spi.check_update >='").append(startTime).append("' and spi.check_update <='").append(endTime).append("') or spi.latest_status in ('0','2')) )  is_check_num, ");
        sqlStr.append(" (select count(*)  from shequ.sqfw_person_info spi  ");
        sqlStr.append(" where spi.household_id=shri.id  ");
        sqlStr.append(" and deleted !=true ");
        sqlStr.append(" and (spi.check_update is null or spi.check_update ='' or  spi.check_update < '").append(startTime).append("' or spi.check_update >'").append(endTime).append("') and spi.latest_status not in ('0','2'))  no_check_num  ");
        sqlStr.append(" from   ");
        sqlStr.append(" shequ.sqfw_household_registration_info shri  ");
        sqlStr.append(" where  ");
        sqlStr.append(" province ='").append(user.getProvince()).append("'");
        sqlStr.append(" and city ='").append(user.getCity()).append("'");
        sqlStr.append(" and district ='").append(user.getDistrict()).append("'");
        sqlStr.append(" and county ='").append(user.getCounty()).append("'");
        sqlStr.append(" and community ='").append(user.getCommunity()).append("'");
        sqlStr.append(" and deleted !=true");
        //户类型
        if (StringUtils.isNotBlank(houseType)) {
            String[] houseTypes = houseType.split(",");
            sqlStr.append(" and (");
            boolean firstParam = true;
            for (String param : houseTypes) {
                if (firstParam) {
                    sqlStr.append("   house_type like '%").append(param).append("%'");
                    firstParam = false;
                } else {
                    sqlStr.append(" or  house_type like '%").append(param).append("%'");
                }
            }
            sqlStr.append(" )");
        }
        //搜索内容
        if (StringUtils.isNotBlank(content)) {
            sqlStr.append("  and ( house_number like '%").append(content).append("%'");//户号
            sqlStr.append("  or household_head like '%").append(content).append("%' )");//户主
            //TODO 预留后期根据家属人名查询出房屋（户号）关联查询
        }
        sqlStr.append(" ) a where 1=1 ");
        //核实情况
        if (StringUtils.isNotBlank(checkStatus)) {
            if ("0".equals(checkStatus)) {
                //未核实
                sqlStr.append(" and ( a.no_check_num >0 or  (a.no_check_num=0 and a.is_check_num = 0))");
                //sqlStrCount.append(" and (check_date is null or check_date ='' or check_date < '").append(startTime).append("')");
            } else if ("1".equals(checkStatus)) {
                //已核实
                sqlStr.append(" and a.no_check_num = 0 and a.is_check_num != 0");
                //sqlStrCount.append(" and  check_date >= '").append(startTime).append("' and check_date <= '").append(endTime).append("'");
            }
        }
        //sqlStr.append(sqlStrCount);
        String sqlStrCount = String.format("( %s ) a", sqlStr);
        int count = this.count(sqlStrCount);
        Integer pageNo = householdRegistrationInfoVO.getPageNo();
        Integer pageSize = householdRegistrationInfoVO.getPageSize();
        //分页查询不传默认查询前20条
        if (null == pageNo) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 20;
        }
        if (pageNo >= 1) {
            pageNo = (pageNo - 1) * pageSize;
        }
        sqlStr.append(" order by a.check_date desc, a.people_number desc");
        sqlStr.append(" LIMIT ").append(pageSize).append(" OFFSET ").append(pageNo);
        Sql sql = Sqls.create(sqlStr.toString());
        List<NutMap> nutMapList = this.listMap(sql);
        Pagination pagination = new Pagination(pageNo, pageSize, count);
        pagination.setList(JSONUtil.toList(JSONUtil.toJsonStr(nutMapList), HouseholdRegistrationInfoVO.class));
        return Result.data(pagination);
    }

    @Override
    public Result<?> getFamilyMembers(String householdId) {
        PersonInfoVO personInfoVO = new PersonInfoVO();
        Cnd cnd = Cnd.NEW();
        cnd.and("household_id", "=", householdId);
        cnd.and("deleted", "!=", true);
        //cnd.orderBy("update_date","desc");
        List<PersonInfo> personInfoList = this.personInfoService.query(cnd);
        int isCheckNum = 0;
        int noCheckNum = 0;
        int totalNum = personInfoList.size();
        //默认空
        personInfoVO.setPersonInfo(Lists.newArrayList());
        personInfoVO.setTotalNum(totalNum);
        personInfoVO.setNoCheckNum(noCheckNum);
        personInfoVO.setIsCheckNum(isCheckNum);
        if (personInfoList.isEmpty()) return Result.data(personInfoVO);
        QuarterEnum quarterEnum = QuarterEnum.getQuarterEnumByMonth(null);

        int startTime = 0;
        int endTime = 0;
        //boolean quarterFlag = false;
        if (!ObjectUtils.isEmpty(quarterEnum)) {
            QueryTimeBuildDTO queryTimeBuildDTO = QuarterEnum.getQuarterEnumAndSetTimeByMonth(quarterEnum);
            startTime = queryTimeBuildDTO.getStartTimeNum();
            endTime = queryTimeBuildDTO.getEndTimeNum();
            //quarterFlag = true;
        }
        List<PersonInfo> personInfos = Lists.newArrayList();
        List<PersonInfo> personInfo_HZ = Lists.newArrayList();//户主
        List<PersonInfo> personInfoJS_no = Lists.newArrayList();//家属
        List<PersonInfo> personInfoJS_is = Lists.newArrayList();//家属

        for (PersonInfo personInfo : personInfoList) {
            Cnd summaryCnd = Cnd.NEW();
            summaryCnd.and("param_data ->>'houseHoldNumber'", "=", personInfo.getHouseHoldNumber());
            summaryCnd.and("param_data ->>'idNumber'", "=", personInfo.getIdNumber());
            summaryCnd.and("param_data ->>'houseHoldId'", "=", personInfo.getHouseholdId());
            summaryCnd.and("type", "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName());
            summaryCnd.and(Sqfw_formSummary_new::getAuditStatus, "=", "submit");
            summaryCnd.and("to_char(fill_date,'yyyyMM')", ">=", String.valueOf(startTime)).and("to_char(fill_date,'yyyyMM')", "<=", String.valueOf(endTime));
            summaryCnd.orderBy("fill_date", "desc");
            Sqfw_formSummary_new summary = this.formsummaryNewService.fetch(summaryCnd);
            boolean no_flag = true;
            if (ObjectUtils.isEmpty(summary)) {
                noCheckNum++;
                personInfo.setCheckStatus("0");
            } else {
                isCheckNum++;
                personInfo.setCheckStatus("1");
                no_flag = false;
            }
            if ("户主".equals(personInfo.getHouseholdHeadRelation())) {
                personInfo_HZ.add(personInfo);
            } else if (no_flag) {
                personInfoJS_no.add(personInfo);
            } else {
                personInfoJS_is.add(personInfo);
            }
        }
        //personInfoList.stream().sorted(Comparator.comparing(PersonInfo::getCheckStatus).reversed()).collect(Collectors.toList());
        personInfos.addAll(personInfo_HZ);
        personInfos.addAll(personInfoJS_no);
        personInfos.addAll(personInfoJS_is);
        personInfoVO.setPersonInfo(personInfos);
        personInfoVO.setTotalNum(totalNum);
        personInfoVO.setNoCheckNum(noCheckNum);
        personInfoVO.setIsCheckNum(isCheckNum);
        return Result.data(personInfoVO);
    }

    @Override
    public Result<?> importHouseholdPersonData(TempFile file) {
       /* try {
            // 1 获取表格的单元格
            Sheet sheet = PoiTlUtil.getBookSheet(file);
            // 2 获取导入的数据
            //List<SqfwShopsBaseInfo> importDatas = getShopInfoImportData(sheet);
            // 获取所有导入的数据
            List<JSONObject> importContents = PoiTlUtil.getImportContent(sheet, 2);
            if (importContents.isEmpty()) {
                return Result.error("无数据！");
            }
            List<String> contentList = org.apache.commons.compress.utils.Lists.newArrayList();
            List<String> householdList = org.apache.commons.compress.utils.Lists.newArrayList();
            Cnd cnd =Cnd.NEW();
            cnd.and(SqfwHouseholdRegistrationInfo::getDeleted,"!=",true);
            List<SqfwHouseholdRegistrationInfo> householdRegistrationInfos = this.query(cnd);
            //过滤出房号
            List<JSONObject> collect = importContents.stream().distinct().filter(json -> "户主".equals(JSONObject.toJavaObject(json, PersonInfo.class).getHouseholdHeadRelation())).collect(Collectors.toList());
            Map<String, SqfwHouseholdRegistrationInfo> personMap = householdRegistrationInfos.stream()
                    .collect(Collectors.toMap(person ->
                                    String.format("%s-%s-%s-%s-%s-%s",
                                            person.getProvince(),
                                            person.getCity(),
                                            person.getDistrict(),
                                            person.getCounty(),
                                            person.getCommunity(),
                                            person.getHouseNumber()),
                            Function.identity()));

            List<SqfwShopsBaseInfo> results = new ArrayList<>();
            int num = 2;
            for (JSONObject json : importContents) {
                num++;
                StringBuilder str = new StringBuilder();
                str.append("第").append(num).append("行").append(":");
                PersonInfo personInfo = JSONObject.toJavaObject(json, PersonInfo.class);
                if (StringUtils.isBlank(personInfo.getProvince()) || StringUtils.isBlank(personInfo.getCity()) || StringUtils.isBlank(personInfo.getDistrict())
                        || StringUtils.isBlank(personInfo.getCounty()) || StringUtils.isBlank(personInfo.getCommunity())) {
                    str.append("【province、city、district、county、community】").append("所属五级不能为空！");
                }
                if (StringUtils.isBlank(personInfo.getHouseHoldNumber())) {
                    str.append("【houseHoldNumber】").append("所属户号不能为空！");
                }
                if (StringUtils.isBlank(personInfo.getIdNumber())) {
                    str.append("【idNumber】").append("身份证不能为空！");
                }
                if (StringUtils.isBlank(personInfo.getHouseholdHeadRelation())) {
                    str.append("【householdHeadRelation】").append("与户主关系不能为空！");
                }
                String key = String.format("%s-%s-%s-%s-%s-%s",personInfo.getProvince(),personInfo.getCity(),personInfo.getDistrict(),personInfo.getCounty(),personInfo.getCommunity(),personInfo.getHouseHoldNumber());
                SqfwHouseholdRegistrationInfo sqfwHouseholdRegistrationInfo = personMap.get(key);
                if(!ObjectUtils.isEmpty(sqfwHouseholdRegistrationInfo)) {
                    personInfo.setHouseholdId(sqfwHouseholdRegistrationInfo.getId());
                }
                StrUtil.handleStrTrim(personInfo);
                personInfo.setCreateBy(SecurityUtil.getUserId());
                if (!ObjectUtils.isEmpty(str)) {
                    contentList.add(str.toString());
                }
            }
            if (!contentList.isEmpty()) {
                return Result.data(ResultCode.FAILURE.getCode(), contentList, "导入的数据有误");
            }
            // 3 新增数据
            this.fastInsert(results);
        } catch (Exception e) {
            throw new ServiceException("异常");
        }*/
        return null;
    }
}
